package com.study.spmongodb.wwj.thread2.char09;

import java.util.Random;

/**
 * @author study
 * @version 1.0
 * @date 2020/12/8 17:11
 */
public class ServerThread extends Thread {

    private final RequestQueue queue;

    private final Random random;

    private volatile boolean flag = true;

    public ServerThread(RequestQueue queue) {
        this.queue = queue;
        this.random = new Random(System.currentTimeMillis());
    }

    @Override
    public void run() {
        while (flag) {
            Request request = queue.getRequest();
            if (null == request) {
                System.out.println("received empty request ...");
                continue;
            }
            System.out.println("Server ---> " + Thread.currentThread().getName() + " " + request.getValue());
            try {
                Thread.sleep(random.nextInt(100));
            } catch (InterruptedException e) {
                return;
            }
        }
    }

    public void close() {
        this.flag = false;
        this.interrupt();
    }
}
